package com.iteaj.iot.test.modbus.dtu;

import com.iteaj.iot.ProtocolType;
import com.iteaj.iot.client.protocol.ServerInitiativeProtocol;
import com.iteaj.iot.modbus.client.ModbusTcpClientCommonProtocol;
import com.iteaj.iot.modbus.client.message.ModbusTcpClientMessage;
import com.iteaj.iot.test.TestProtocolType;

/**
 * 模拟modbus 主节点协议
 */
public class ModbusDtuClientTestProtocol extends ServerInitiativeProtocol<ModbusDtuClientTestMessage> {

    private ModbusTcpClientMessage message;

    public ModbusDtuClientTestProtocol(ModbusDtuClientTestMessage requestMessage) {
        super(requestMessage);
    }

    @Override
    protected void doBuildRequestMessage(ModbusDtuClientTestMessage requestMessage) {
        requestMessage.getHead().setMessageId(null);
        ModbusTcpClientCommonProtocol commonProtocol = ModbusTcpClientCommonProtocol.build(requestMessage.getHead(), requestMessage.getBody());
        commonProtocol.sync(2000).request();
        this.message = commonProtocol.responseMessage();
    }

    @Override
    protected ModbusDtuClientTestMessage doBuildResponseMessage() {
        return new ModbusDtuClientTestMessage(this.message.getHead(), this.message.getBody());
    }

    @Override
    public ProtocolType protocolType() {
        return TestProtocolType.PIReq;
    }
}
